import { Injectable, Inject } from '@nestjs/common';
import { Redis, RedisKey } from 'ioredis';

type StringValue = string | number | Buffer;

/** redis 基础服务类 */
@Injectable()
export class RedisService {
  constructor(@Inject('REDIS_CLIENT') private readonly redisClient: Redis) {}

  /** 字符串普通存储 */
  public async setString(key: RedisKey, value: StringValue) {
    return await this.redisClient.set(key, value);
  }

  /** 字符串存储并设置过期时间 */
  public async setStringWithEx(key: RedisKey, expireIn: number | string, value: StringValue) {
    return await this.redisClient.setex(key, expireIn, value);
  }

  /** 获取指定key的字符串 */
  public async getString(key: RedisKey) {
    return await this.redisClient.get(key);
  }

  /** 删除指定key的字符串 */
  public async delString(key: RedisKey) {
    return await this.redisClient.del(key);
  }

  /** 获取多个key */
  public async mget(keys: RedisKey[]) {
    return this.redisClient.mget(keys);
  }

  /** 生成自增key */
  public async genIncrKey(key: RedisKey) {
    return await this.redisClient.incr(key);
  }
}
